package com.archive.forum.controller;

import com.archive.forum.dto.AccessTokenDTO;
import com.archive.forum.dto.GithubUser;
import com.archive.forum.mapper.UserMapper;
import com.archive.forum.model.User;
import com.archive.forum.provider.GithubProvider;
import com.archive.forum.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

//三方登录控制
@Controller
public class AuthorizeController {
    @Autowired
    private GithubProvider githubProvider;
    @Value("${github.client.id}")
    private String clientId;
    @Value("${github.client.secret}")
    private String clientSecret;
    @Value("${github.redirect.uri}")
    private String redirectUri;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;
    @GetMapping("/callback")
    // 处理GitHub回调请求
    public String callback(@RequestParam(name = "code") String code,
                           @RequestParam(name = "state") String state,
                           HttpServletResponse response, HttpServletRequest request, Model model){
        User user = (User) request.getSession().getAttribute("user");
        // 创建AccessTokenDTO对象
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        // 设置client_id
        accessTokenDTO.setClient_id(clientId);
        // 设置client_secret
        accessTokenDTO.setClient_secret(clientSecret);
        // 设置code
        accessTokenDTO.setCode(code);
        // 设置redirect_uri
        accessTokenDTO.setRedirect_uri(redirectUri);
        // 设置state
        accessTokenDTO.setState(state);
        // 获取access_token
        String accessToken = githubProvider.getAccessToken(accessTokenDTO);
        // 获取用户信息
        GithubUser githubUser = githubProvider.getUser(accessToken);
        if(githubUser != null && githubUser.getId() != null){
            //创建或更新用户
            return userService.githubLogin(githubUser, response,user,model);
        }
        return "redirect:/";
    }
}
